#include "sem.h"

int semid;
struct sembuf sops;

int sem_create(unsigned int snums,unsigned short *vals)
{
    key_t key = ftok(PATH_NAME,66);
    if(-1 == key)
    {
        perror("ftok error");
        return -1;
    }
    semid = semget(key,snums,IPC_CREAT|0666);
    if(-1 == semid)
    {
        perror("semget error");
        return -1;
    }
    int ret = semctl(semid,0,SETALL,vals);
    if(-1 == ret)
    {
        perror("semctl error");
        return -1;
    }
    return 0;
}

int sem_occupy(int semnum)
{
    sops.sem_num = semnum;
    sops.sem_op = -1;
    sops.sem_flg = SEM_UNDO;
    if(-1 == semop(semid,&sops,1))
    {
        perror("semop error");
        return -1;
    }
    return 0;
}

int sem_release(int semnum)
{
    sops.sem_num = semnum;
    sops.sem_op = 1;
    sops.sem_flg = SEM_UNDO;
    if(-1 == semop(semid,&sops,1))
    {
        perror("semop error");
        return -1;
    }
    return 0;
}

void sem_delete(){
    semctl(semid,0,IPC_RMID,NULL);
}
